<template>
  <XenPageLayout title="访客预约详情" title-align="left">
    <div class="detail">
      <view class="detail-card">
        <!-- 访问凭证（如果状态已通过且有二维码） -->
        <!-- <view
          class="section"
          v-if="appointmentDetail.Entity.BillStatus === '10'"
        >
          <view class="section-title">访问凭证</view>
          <view class="qrcode-container">
            <image
              v-if="qrcodeUrl"
              class="qrcode"
              :src="qrcodeUrl"
              mode="aspectFit"
              alt="二维码"
            ></image>
            <view v-else class="loading-qrcode">
              <uni-icons type="refresh" size="30" :spin="true"></uni-icons>
              <text>二维码加载中...</text>
            </view>
            <view class="qrcode-tip">出示此码给门卫验证</view>
          </view>
        </view> -->
        <view class="section">
          <view class="section-title">预约信息</view>
          <view class="info-item">
            <text class="label">访客事由</text>
            <text class="value">{{
              appointmentDetail.Entity.VisitorReason?.ReasonName || ""
            }}</text>
          </view>
          <view class="info-item">
            <text class="label">预约时间</text>
            <text class="value">{{
              formatDateTime(appointmentDetail.Entity.ReservationTime) || ""
            }}</text>
          </view>
          <view class="info-item">
            <text class="label">接待人</text>
            <text class="value">{{
              appointmentDetail.Entity.Receptionist || ""
            }}</text>
          </view>
          <view class="info-item">
            <text class="label">接待人电话</text>
            <text class="value">{{
              appointmentDetail.Entity.ReceptionistPhone || ""
            }}</text>
          </view>
          <view class="info-item" v-if="appointmentDetail.Entity.Remark">
            <text class="label">备注</text>
            <text class="value">{{
              appointmentDetail.Entity.Remark || ""
            }}</text>
          </view>
          <view class="info-item">
            <text class="label">预约状态</text>
            <text class="value">{{
              getWorkflowStatusText(appointmentDetail.Entity.WorkflowStatus)
            }}</text>
          </view>
        </view>

        <view class="section">
          <view class="section-title">基本信息</view>
          <view class="info-item">
            <text class="label">姓名</text>
            <text class="value">{{ appointmentDetail.Entity.Name || "" }}</text>
          </view>
          <view class="info-item">
            <text class="label">手机号</text>
            <text class="value">{{
              appointmentDetail.Entity.Phone || ""
            }}</text>
          </view>
          <view class="info-item">
            <text class="label">身份证号</text>
            <text class="value">{{
              appointmentDetail.Entity.IdCardNo || ""
            }}</text>
          </view>
          <view
            class="info-item"
            v-if="appointmentDetail.Entity.IdCardFrontPhoto"
          >
            <text class="label">身份证照片</text>
            <image
              class="id-photo"
              :src="getImageUrl(appointmentDetail.Entity.IdCardFrontPhotoId)"
              mode="aspectFit"
              @tap="
                previewIdCard(
                  getImageUrl(appointmentDetail.Entity.IdCardFrontPhotoId),
                )
              "
            ></image>
          </view>
          <view class="info-item">
            <text class="label">所属单位/公司</text>
            <text class="value">{{
              appointmentDetail.Entity.Company || ""
            }}</text>
          </view>
          <view class="info-item" v-if="appointmentDetail.Entity.CarNo">
            <text class="label">车牌号</text>
            <text class="value">{{
              appointmentDetail.Entity.CarNo || ""
            }}</text>
          </view>
        </view>

        <!-- 审核时间线组件 - 所有用户都有权限查看 -->
        <XenAuditTimeline :steps="timelineData" />
      </view>
    </div>

    <!-- 审核操作按钮组件 - 根据IsMyApprove字段控制显示 -->
    <XenAuditActions
      v-if="appointmentDetail.IsMyApprove"
      :actions="auditActions"
      @action="handleAuditAction"
    />
  </XenPageLayout>
</template>

<script lang="ts" setup>
import XenPageLayout from "@/layouts/XenPageLayout.vue";
import XenAuditTimeline from "@/components/XenAuditTimeline.vue";
import XenAuditActions from "@/components/XenAuditActions.vue";
import { ref, computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { formatDateTime } from "../../../utils/xenUtils";
import SysVisitorReasonApi from "./api/index";
import type { IDetailsResponse } from "./api/interface";
import commonApi from "@/api/common";
import type { QueryTimeline, WorkflowInfo } from "@/type/common";

// 预约详情数据
const appointmentDetail = ref<IDetailsResponse>({} as IDetailsResponse);
const id = ref<string>("");
const qrcodeUrl = ref<string>("");

// 审核相关数据
const timelineData = ref<WorkflowInfo[]>([]);

// 创建通用API实例
const commonApiInstance = commonApi();

// 注意：现在直接使用 timelineData，不需要转换

// 审核操作按钮配置
const auditActions = computed(() => [
  {
    key: "approve",
    label: "通过",
    type: "success" as const,
    icon: "checkmarkempty",
    primary: true,
  },
  {
    key: "reject",
    label: "拒绝",
    type: "danger" as const,
    icon: "closeempty",
    primary: true,
  },
  {
    key: "return",
    label: "退回",
    type: "warning" as const,
    icon: "undo",
  },
  {
    key: "transfer",
    label: "转办",
    type: "default" as const,
    icon: "forward",
  },
]);

// 注意：时间线状态转换逻辑已移至 XenAuditTimeline 组件内部

// 获取时间线数据
const getTimelineData = async () => {
  if (!id.value) return;

  try {
    const params: QueryTimeline = {
      entityId: id.value,
      entitytype: "HengTong.Model.Db.Bill.SysVisitorRecordRequestBill",
    };

    const response = await commonApiInstance.getTimeline(params);
    // 现在 response 应该是 WorkflowInfo[] 类型
    timelineData.value = response || [];
  } catch (error) {
    console.error("获取时间线数据失败:", error);
    timelineData.value = [];
  }
};

// 处理审核操作
const handleAuditAction = (action: any, remark?: string) => {
  console.log("审核操作:", action, "审批原因:", remark);

  switch (action.key) {
    case "approve":
      handleApprove(remark);
      break;
    case "reject":
      handleReject(remark);
      break;
    case "return":
      handleReturn();
      break;
    case "transfer":
      handleTransfer();
      break;
    default:
      console.log("未知操作:", action.key);
  }
};

// 审核通过
const handleApprove = (remark?: string) => {
  // 直接执行同意操作，因为审批原因已经在组件中收集
  // TODO: 调用审核通过接口，传递审批原因参数
  console.log("执行审核通过，审批原因:", remark);
  uni.showToast({
    title: "审核通过",
    icon: "success",
  });
};

// 审核拒绝
const handleReject = (remark?: string) => {
  // 直接执行拒绝操作，因为审批原因已经在组件中收集
  // TODO: 调用审核拒绝接口，传递审批原因参数
  console.log("执行审核拒绝，审批原因:", remark);
  uni.showToast({
    title: "审核拒绝",
    icon: "success",
  });
};

// 退回
const handleReturn = () => {
  uni.showToast({
    title: "退回功能开发中",
    icon: "none",
  });
};

// 转办
const handleTransfer = () => {
  uni.showToast({
    title: "转办功能开发中",
    icon: "none",
  });
};

// 获取图片URL
const getImageUrl = (fileId: string) => {
  if (!fileId) return "";
  return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
};

// 获取预约详情
const getappointmentdetail = async () => {
  if (!id.value) return;

  try {
    const api = SysVisitorReasonApi();
    const res = await api.details(id.value);

    appointmentDetail.value = res;

    // 获取时间线数据
    await getTimelineData();

    // 如果状态是已审核且有ID，生成二维码（暂时保留逻辑）
    if (
      appointmentDetail.value.Entity.BillStatus === "10" &&
      appointmentDetail.value.Entity.ID
    ) {
      generateQRCode();
    }
  } catch (error) {
    console.error("获取预约详情失败:", error);
    uni.showToast({
      title: "获取预约详情失败",
      icon: "none",
    });
  }
};

// 生成二维码（暂时保留，等后端完善）
const generateQRCode = () => {
  try {
    if (!appointmentDetail.value.Entity.ID) {
      console.error("无法获取预约ID");
      return;
    }

    const apiUrl = import.meta.env.VITE_BASE_URL;
    const qrContent = encodeURIComponent(
      `${apiUrl}/r/w?cmd=visitorJump.addRecordAndInfo&recordId=${appointmentDetail.value.Entity.ID}`,
    );

    const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=${qrContent}`;
    qrcodeUrl.value = qrCodeUrl;
  } catch (error) {
    console.error("二维码生成失败:", error);
    uni.showToast({
      title: "二维码生成失败",
      icon: "none",
    });
  }
};

// 使用 onLoad 生命周期钩子获取页面参数
onLoad((options: any) => {
  if (options) {
    // 统一使用 id 参数（从待办中心、消息通知和列表页跳转）
    if (options.id) {
      id.value = options.id;
      getappointmentdetail();
    } else {
      uni.showToast({
        title: "缺少记录ID参数",
        icon: "none",
      });
    }
  } else {
    uni.showToast({
      title: "缺少页面参数",
      icon: "none",
    });
  }
});

// 获取工作流状态对应的文本描述
const getWorkflowStatusText = (status: string | undefined): string => {
  const statusMap: Record<string, string> = {
    待提交: "待提交",
    提交中: "提交中",
    审核中: "审核中",
    已完成: "已完成",
    已取消: "已取消",
  };
  return statusMap[status || ""] || "未知状态";
};

// 预览身份证照片
const previewIdCard = (url: string) => {
  if (typeof url === "string" && url) {
    uni.previewImage({
      urls: [url],
      current: url,
      indicator: "default",
      showmenu: false,
      loop: false,
      success: () => {},
      fail: (err) => {
        console.error("预览失败", err);
        uni.showToast({
          title: "图片预览失败",
          icon: "none",
        });
      },
    });
  } else {
    uni.showToast({
      title: "无效的图片链接",
      icon: "none",
    });
  }
};
</script>

<style lang="scss" scoped>
.detail {
  padding: 0 0 40rpx;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.detail-card {
  background-color: #ffffff;
  border-radius: 20rpx;
  margin: 0 20rpx;
  overflow: hidden;
}

.section {
  padding: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  position: relative;
  padding-left: 20rpx;

  &:before {
    content: "";
    position: absolute;
    left: 0;
    top: 8rpx;
    height: 32rpx;
    width: 8rpx;
    background-color: #b88e67;
  }
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
  align-items: flex-start;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    width: 200rpx;
    font-size: 28rpx;
    color: #666;
    flex-shrink: 0;
  }

  .value {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    word-break: break-all;

    &.status-0 {
      color: #faad14;
    }
    &.status-10 {
      color: #52c41a;
    }
    &.status-11 {
      color: #f5222d;
    }
    &.status-12 {
      color: #f5222d;
    }
    &.status-20 {
      color: #1890ff;
    }
    &.status-21 {
      color: #999999;
    }
  }
}

.id-photo {
  width: 300rpx;
  height: 200rpx;
  background-color: #f0f0f0;
  border-radius: 8rpx;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
}

.qrcode-canvas {
  width: 300rpx;
  height: 300rpx;
  background-color: #ffffff;
  margin-bottom: 20rpx;
}

.qrcode {
  width: 300rpx;
  height: 300rpx;
  background-color: #f0f0f0;
  margin-bottom: 20rpx;
}

.loading-qrcode {
  width: 300rpx;
  height: 300rpx;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-bottom: 20rpx;
  color: #999;

  text {
    margin-top: 20rpx;
    font-size: 26rpx;
  }
}

.qrcode-tip {
  font-size: 28rpx;
  color: #666;
}
</style>
